package com.seqb.manage.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seqb.common.ResultVo;
import com.seqb.common.mybatis.WrapperHandler;
import com.seqb.exception.BdException;
import com.seqb.manage.user.dao.UserDao;
import com.seqb.manage.user.dao.UserRoleDao;
import com.seqb.manage.user.domain.UserDO;
import com.seqb.manage.user.domain.UserRoleDO;
import com.seqb.manage.user.service.UserRoleService;
import com.seqb.manage.user.service.UserService;
import com.seqb.utils.Md5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/15
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserDO get(Long id) {
        return userDao.selectById(id);
    }

    @Override
    public Page<UserDO> list(Map<String, Object> map) {
        if (null != map && null != map.get("pageNumber") && null != map.get("pageSize")) {
            PageHelper.startPage(Integer.valueOf(map.get("pageNumber").toString()), Integer.valueOf(map.get("pageSize").toString()));
        } else {
            PageHelper.startPage(1, Integer.MAX_VALUE);
        }
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, UserDO.class);
        return (Page<UserDO>) userDao.selectList(queryWrapper);
    }

    @Override
    public int count(Map<String, Object> map) {
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, UserDO.class);
        return userDao.selectCount(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo save(UserDO user) {
        try {
            //新增用户操作
            String username = user.getUsername();
            String account = user.getAccount();
            String password = user.getPassword();
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
                return ResultVo.error("参数不足！");
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("account", account);
            UserDO userDO = userDao.selectOne(queryWrapper);
            if (null != userDO) {
                return ResultVo.error("该账号已存在，请重新输入！");
            }
            user.setPassword(Md5Utils.encrypt(password));
            int insert = userDao.insert(user);
            if (insert <= 0) {
                throw new BdException("操作失败！");
            }
            //先删除用户角色
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", user.getId());
            userRoleDao.delete(queryWrapper);
            //再用户角色分配
            String roleIds = user.getIds();
            if (StringUtils.isNotEmpty(roleIds)) {
                String[] strRoleIds = roleIds.split(",");
                List<UserRoleDO> userRoleList = new ArrayList<>();
                for (String roleId : strRoleIds) {
                    if (StringUtils.isEmpty(roleId)) {
                        continue;
                    }
                    UserRoleDO userRole = new UserRoleDO();
                    userRole.setRoleId(Long.valueOf(roleId));
                    userRole.setUserId(user.getId());
                    userRoleList.add(userRole);
                }
                if (userRoleList.size() > 0) {
                    boolean batch = userRoleService.saveBatch(userRoleList);
                    if (!batch) {
                        throw new BdException("操作失败！");
                    }
                }
            }
            return ResultVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultVo.error("操作失败！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo update(UserDO user) {
        try {
            //修改用户操作
            int update = 0;
            Long id = user.getId();
            if (null == id) {
                return ResultVo.error("参数不足！");
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            String account = user.getAccount();
            if (StringUtils.isNotEmpty(account)) {
                queryWrapper.eq("account", account);
                UserDO existDO = userDao.selectOne(queryWrapper);
                if (null != existDO && !id.equals(existDO.getId())) {
                    return ResultVo.error("该账号已存在，请重新输入！");
                }
            }
            UserDO existDO = userDao.selectById(id);
            if (null == existDO) {
                return ResultVo.error("数据不存在！");
            }
            String clearField = user.getClearField();
            if (StringUtils.isEmpty(clearField)) {
                update = userDao.updateById(user);
            } else {
                UpdateWrapper updateWrapper = WrapperHandler.genUpdateWrapper(user);
                updateWrapper.eq("id", id);
                update = userDao.update(user, updateWrapper);
            }
            if (update <= 0) {
                throw new BdException("操作失败！");
            }
            //先删除用户角色
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", user.getId());
            userRoleDao.delete(queryWrapper);
            //再用户角色分配
            String roleIds = user.getIds();
            if (StringUtils.isNotEmpty(roleIds)) {
                String[] strRoleIds = roleIds.split(",");
                List<UserRoleDO> userRoleList = new ArrayList<>();
                for (String roleId : strRoleIds) {
                    if (StringUtils.isEmpty(roleId)) {
                        continue;
                    }
                    UserRoleDO userRole = new UserRoleDO();
                    userRole.setRoleId(Long.valueOf(roleId));
                    userRole.setUserId(user.getId());
                    userRoleList.add(userRole);
                }
                if (userRoleList.size() > 0) {
                    boolean batch = userRoleService.saveBatch(userRoleList);
                    if (!batch) {
                        throw new BdException("操作失败！");
                    }
                }
            }

            return ResultVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultVo.error("操作失败！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(Long id) {
        return userDao.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchRemove(Long[] ids) {
        return userDao.deleteBatchIds(Arrays.asList(ids));
    }

}
